package com.heima.wemedia.gateway.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemeida.pojos.WmUser;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.Payload;
import com.heima.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;

/**
 * 鉴权过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter,Ordered{
    @Value("${leadnews.jwt.publicKeyPath}")
    public String publicKeyPath;
    /**
     * 过滤逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否登录请求，是则直接放行
        //获取请求路径
        String uri = request.getURI().getPath();   // /user/api/v1/login/login_auth
        if(uri.contains("/login")){
            //放行
            return chain.filter(exchange); // 注意：必须要return，否则无法放行
        }

        //从请求头获取token
        String token = request.getHeaders().getFirst("token");

        //判断token是否为空，为空，则返回401，拒绝访问
        if(StringUtils.isEmpty(token)){
            //返回401，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();  // 终止请求
        }

        //校验token是否合法有效（RSA公钥解密token）
        //获取RSA公钥
        try {
            PublicKey publicKey = RsaUtils.getPublicKey(publicKeyPath);
            //校验并获取用户信息
            Payload<WmUser> payload = JwtUtils.getInfoFromToken(token, publicKey, WmUser.class);

            //取出当前登录用户ID
            WmUser user = payload.getInfo();

            //存入请求头
            request.mutate().header("userId", user.getId().toString());

            //有效，则放行
            return chain.filter(exchange);
        } catch (Exception e) {
            //无效，则返回401，拒绝访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();  // 终止请求
        }
    }

    /**
     * 设置过滤器优先级方法
     * @return 返回整数，数值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
